#include "dormitorymanage.h"
#include "mainwindow.h"
#include "database.h"

DormitoryManage::DormitoryManage(MainWindow *parent)
    : QWidget(parent), mainWindow(parent), isEditMode(false)
{
    // 获取数据库实例
    database = mainWindow->getDatabase();

    setupUi();
    refreshData();
}

DormitoryManage::~DormitoryManage()
{
}

void DormitoryManage::setupUi()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 单元管理区域
    QGroupBox *unitGroup = new QGroupBox("单元管理", this);
    QHBoxLayout *unitLayout = new QHBoxLayout(unitGroup);

    QLabel *unitSelectLabel = new QLabel("选择单元:", this);
    unitComboBox = new QComboBox(this);
    unitComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    QLabel *unitNameLabel = new QLabel("单元名称:", this);
    unitNameEdit = new QLineEdit(this);

    addUnitButton = new QPushButton("添加单元", this);
    addUnitButton->setStyleSheet("background-color: #28a745; color: white; padding: 5px 15px;");

    deleteUnitButton = new QPushButton("删除单元", this);
    deleteUnitButton->setStyleSheet("background-color: #dc3545; color: white; padding: 5px 15px;");

    unitLayout->addWidget(unitSelectLabel);
    unitLayout->addWidget(unitComboBox);
    unitLayout->addSpacing(20);
    unitLayout->addWidget(unitNameLabel);
    unitLayout->addWidget(unitNameEdit);
    unitLayout->addWidget(addUnitButton);
    unitLayout->addWidget(deleteUnitButton);

    mainLayout->addWidget(unitGroup);

    // 房间管理区域
    QGroupBox *roomGroup = new QGroupBox("房间管理", this);
    QVBoxLayout *roomVLayout = new QVBoxLayout(roomGroup);

    // 房间操作区域
    QHBoxLayout *roomControlLayout = new QHBoxLayout();

    QLabel *roomNumberLabel = new QLabel("房间号:", this);
    roomNumberEdit = new QLineEdit(this);

    addRoomButton = new QPushButton("添加房间", this);
    addRoomButton->setStyleSheet("background-color: #28a745; color: white; padding: 5px 15px;");

    editRoomButton = new QPushButton("修改房间", this);
    editRoomButton->setStyleSheet("background-color: #ffc107; color: white; padding: 5px 15px;");
    editRoomButton->setEnabled(false);

    deleteRoomButton = new QPushButton("删除房间", this);
    deleteRoomButton->setStyleSheet("background-color: #dc3545; color: white; padding: 5px 15px;");
    deleteRoomButton->setEnabled(false);

    roomControlLayout->addWidget(roomNumberLabel);
    roomControlLayout->addWidget(roomNumberEdit);
    roomControlLayout->addWidget(addRoomButton);
    roomControlLayout->addWidget(editRoomButton);
    roomControlLayout->addWidget(deleteRoomButton);

    roomVLayout->addLayout(roomControlLayout);

    // 房间列表表格
    roomsTable = new QTableWidget(this);
    roomsTable->setColumnCount(2);
    roomsTable->setHorizontalHeaderLabels(QStringList() << "房间号" << "操作");
    roomsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    roomsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    roomsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    roomsTable->verticalHeader()->setVisible(false);

    roomVLayout->addWidget(roomsTable);

    mainLayout->addWidget(roomGroup);

    // 连接信号和槽
    connect(unitComboBox, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
            this, &DormitoryManage::onUnitSelected);
    connect(addUnitButton, &QPushButton::clicked, this, &DormitoryManage::onAddUnitClicked);
    connect(deleteUnitButton, &QPushButton::clicked, this, &DormitoryManage::onDeleteUnitClicked);
    connect(addRoomButton, &QPushButton::clicked, this, &DormitoryManage::onAddRoomClicked);
    connect(editRoomButton, &QPushButton::clicked, this, &DormitoryManage::onEditRoomClicked);
    connect(deleteRoomButton, &QPushButton::clicked, this, &DormitoryManage::onDeleteRoomClicked);
    connect(roomsTable, &QTableWidget::cellClicked, this, &DormitoryManage::onRoomTableItemClicked);
}

void DormitoryManage::refreshData()
{
    loadUnits();
}

void DormitoryManage::loadUnits()
{
    // 保存当前选择的单元
    QString currentSelectedUnit = unitComboBox->currentText();

    // 清空单元选择
    unitComboBox->clear();

    // 加载单元列表
    QStringList units = database->getBuildingUnits();
    unitComboBox->addItems(units);

    // 尝试恢复之前选择的单元
    int index = unitComboBox->findText(currentSelectedUnit);
    if (index >= 0)
    {
        unitComboBox->setCurrentIndex(index);
    }
}

void DormitoryManage::loadRooms()
{
    // 清空表格
    roomsTable->setRowCount(0);

    if (currentUnit.isEmpty())
    {
        return;
    }

    // 获取当前单元的房间列表
    QStringList rooms = database->getRoomsByUnit(currentUnit);

    roomsTable->setRowCount(rooms.size());

    for (int i = 0; i < rooms.size(); ++i)
    {
        QTableWidgetItem *roomItem = new QTableWidgetItem(rooms[i]);
        roomsTable->setItem(i, 0, roomItem);

        // 添加选择按钮
        QTableWidgetItem *selectItem = new QTableWidgetItem("选择");
        selectItem->setTextAlignment(Qt::AlignCenter);
        selectItem->setForeground(QColor(0, 123, 255));
        roomsTable->setItem(i, 1, selectItem);
    }
}

void DormitoryManage::onUnitSelected(const QString &unit)
{
    currentUnit = unit;
    loadRooms();

    // 清空选择的房间
    currentRoom = "";
    roomNumberEdit->clear();
    originalRoomNumber = "";
    isEditMode = false;

    // 禁用编辑和删除按钮
    editRoomButton->setEnabled(false);
    deleteRoomButton->setEnabled(false);

    // 更新添加按钮文本
    addRoomButton->setText("添加房间");
}

void DormitoryManage::onAddUnitClicked()
{
    QString unitName = unitNameEdit->text().trimmed();

    if (unitName.isEmpty())
    {
        QMessageBox::warning(this, "错误", "请输入单元名称");
        return;
    }

    // 检查是否已存在相同名称的单元
    QStringList units = database->getBuildingUnits();
    if (units.contains(unitName))
    {
        QMessageBox::warning(this, "错误", "已存在同名单元");
        return;
    }

    // 添加单元
    if (database->addUnit(unitName))
    {
        QMessageBox::information(this, "成功", "单元添加成功");

        // 清空输入框
        unitNameEdit->clear();

        // 刷新单元列表
        loadUnits();

        // 选中新添加的单元
        int index = unitComboBox->findText(unitName);
        if (index >= 0)
        {
            unitComboBox->setCurrentIndex(index);
        }
    }
    else
    {
        QMessageBox::critical(this, "错误", "单元添加失败");
    }
}

void DormitoryManage::onDeleteUnitClicked()
{
    if (currentUnit.isEmpty())
    {
        QMessageBox::warning(this, "错误", "请先选择要删除的单元");
        return;
    }

    // 确认删除
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除",
                                                              QString("确定要删除单元 %1 吗？").arg(currentUnit),
                                                              QMessageBox::Yes | QMessageBox::No);

    if (reply != QMessageBox::Yes)
    {
        return;
    }

    // 尝试删除单元
    if (database->deleteUnit(currentUnit))
    {
        QMessageBox::information(this, "成功", "单元删除成功");

        // 刷新单元列表
        loadUnits();
    }
    else
    {
        QMessageBox::critical(this, "错误",
                              "删除失败，该单元下可能还有房间，请先删除关联的房间");
    }
}

void DormitoryManage::onAddRoomClicked()
{
    if (currentUnit.isEmpty())
    {
        QMessageBox::warning(this, "错误", "请先选择单元");
        return;
    }

    QString roomNumber = roomNumberEdit->text().trimmed();

    if (roomNumber.isEmpty())
    {
        QMessageBox::warning(this, "错误", "请输入房间号");
        return;
    }

    // 如果是编辑模式
    if (isEditMode)
    {
        // 检查新房间号是否已存在
        QStringList rooms = database->getRoomsByUnit(currentUnit);
        if (rooms.contains(roomNumber) && roomNumber != originalRoomNumber)
        {
            QMessageBox::warning(this, "错误", "该单元下已存在同名房间");
            return;
        }

        // 更新房间号
        if (database->updateRoom(currentUnit, originalRoomNumber, roomNumber))
        {
            QMessageBox::information(this, "成功", "房间号修改成功");

            // 清空输入框并重置状态
            roomNumberEdit->clear();
            isEditMode = false;
            originalRoomNumber = "";
            addRoomButton->setText("添加房间");

            // 刷新房间列表
            loadRooms();
        }
        else
        {
            QMessageBox::critical(this, "错误", "房间号修改失败");
        }
    }
    else
    {
        // 添加新房间
        // 检查是否已存在相同的房间号
        QStringList rooms = database->getRoomsByUnit(currentUnit);
        if (rooms.contains(roomNumber))
        {
            QMessageBox::warning(this, "错误", "该单元下已存在同名房间");
            return;
        }

        // 添加房间
        if (database->addRoom(currentUnit, roomNumber))
        {
            QMessageBox::information(this, "成功", "房间添加成功");

            // 清空输入框
            roomNumberEdit->clear();

            // 刷新房间列表
            loadRooms();
        }
        else
        {
            QMessageBox::critical(this, "错误", "房间添加失败");
        }
    }
}

void DormitoryManage::onEditRoomClicked()
{
    if (currentRoom.isEmpty())
    {
        return;
    }

    // 进入编辑模式
    isEditMode = true;
    originalRoomNumber = currentRoom;

    // 将当前房间号填入编辑框
    roomNumberEdit->setText(currentRoom);
    roomNumberEdit->setFocus();

    // 更新按钮文本
    addRoomButton->setText("保存修改");
}

void DormitoryManage::onDeleteRoomClicked()
{
    if (currentRoom.isEmpty())
    {
        return;
    }

    // 确认删除
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除",
                                                              QString("确定要删除房间 %1 吗？").arg(currentRoom),
                                                              QMessageBox::Yes | QMessageBox::No);

    if (reply != QMessageBox::Yes)
    {
        return;
    }

    // 检查房间是否有关联的评分记录
    if (database->hasScoreRecords(currentUnit, currentRoom))
    {
        // 询问是否删除关联的评分记录
        QMessageBox::StandardButton delRecordsReply = QMessageBox::question(this, "关联数据",
                                                                            "该房间存在关联的评分记录，是否一并删除？",
                                                                            QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);

        if (delRecordsReply == QMessageBox::Cancel)
        {
            return;
        }

        if (delRecordsReply == QMessageBox::Yes)
        {
            // 删除关联的评分记录
            database->deleteRelatedScoreRecords(currentUnit, currentRoom);
        }
    }

    // 删除房间
    if (database->deleteRoom(currentUnit, currentRoom))
    {
        QMessageBox::information(this, "成功", "房间删除成功");

        // 清空当前选择的房间
        currentRoom = "";
        roomNumberEdit->clear();

        // 禁用编辑和删除按钮
        editRoomButton->setEnabled(false);
        deleteRoomButton->setEnabled(false);

        // 刷新房间列表
        loadRooms();
    }
    else
    {
        QMessageBox::critical(this, "错误", "房间删除失败");
    }
}

void DormitoryManage::onRoomTableItemClicked(int row, int column)
{
    // 获取点击的房间号
    QTableWidgetItem *roomItem = roomsTable->item(row, 0);
    if (!roomItem)
    {
        return;
    }

    currentRoom = roomItem->text();

    // 启用编辑和删除按钮
    editRoomButton->setEnabled(true);
    deleteRoomButton->setEnabled(true);

    // 如果点击的是"选择"列，并且不是编辑模式，填充房间号到编辑框
    if (column == 1 && !isEditMode)
    {
        roomNumberEdit->setText(currentRoom);
    }
}